<?php

namespace Portal\ContraCulturaBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Portal\ContraCulturaBundle\Entity\User;
use Portal\ContraCulturaBundle\Form\UserType;
use Portal\ContraCulturaBundle\Entity\Role;


class UserController extends Controller
{

	/* =========================== ROLE_SUPER =========================== */
	
	public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('PortalContraCulturaBundle:User')->findAll();

        return $this->render('PortalContraCulturaBundle:User:index.html.twig',array(
            'entities' => $entities,
        ));
    }    
    
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('PortalContraCulturaBundle:User')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Usuario entity.');        
        }
        
        return $this->render("PortalContraCulturaBundle:User:show.html.twig", array(
            'entity' => $entity
        ));
    }
    
    public function newAction()
    {
    	$user = new User();
    	$form = $this->createForm(new UserType(), $user);
    	return $this->render('PortalContraCulturaBundle:User:user.html.twig', array (
    			'form' => $form->createView(),   
				'user' => $user,
    	));    	
    }

    public function editAction($id)
    {
    	$em = $this->getDoctrine()->getManager();
    	$user = $em->getRepository("PortalContraCulturaBundle:User")->find($id);
    	
    	$form = $this->createForm(new UserType(), $user);
        return $this->render('PortalContraCulturaBundle:User:user.html.twig', array (
        		'form' => $form->createView(),  
				'user' => $user,
        )); 
    }
    
    public function deleteConfirmAction($id)
    {
    	$em = $this->getDoctrine()->getManager();
    	$user = $em->getRepository("PortalContraCulturaBundle:User")->find($id);
		
		return $this->render('PortalContraCulturaBundle:User:confirm-delete.html.twig', array(
				'user' => $user
		));
    }
    
    public function deleteAction(Request $request)
    {
    	
    }
    
    /* =========================== ROLE_USER =========================== */
    
    public function saveAction(Request $request)
    {
    	$user = new User();
    	$form = $this->createForm(new UserType(), $user);
    	
    	if($request->isMethod('POST')){
    		$form->bind($request);
    		
    		$em = $this->getDoctrine()->getManager();
    		$repository = $this->getDoctrine()->getRepository('PortalContraCulturaBundle:User');
    		
    		// Verifica se foi preenchida uma nova senha
    		if($user->getPassword()){
    			//Pega o factory
    			$factory = $this->get('security.encoder_factory');
    			//gera um encoder
    			$encoder = $factory->getEncoder($user);
    			//codifica senha
    			$pass = $encoder->encodePassword($user->getPassword(), $user->getSalt());
    			 
    			//Adiciona a senha codificada
    			$user->setPassword($pass);
    		}
    		else{
    			$userOld = $em->getRepository("PortalContraCulturaBundle:User")->find($user->getId());
    			$user->setPassword($userOld->getPassword());
    		}
    		
    		// Atualização
    		if($user->getId()){
    			try{
    				$em->merge($user);
    				$em->flush();
    				
    				$this->get('session')->getFlashBag()->add('msg_sucesso', "Usuário atualizado com sucesso!");
    			}
    			catch (Exception $e) {
    				$this->get('session')->getFlashBag()->add('msg_falha', "Falha ao atualizar o usuário!");
    			}
    		}
    		// Inserção
    		else{
    			try{
    				$em->persist($user);
    				$em->flush();
    				
    				$this->get('session')->getFlashBag()->add('msg_sucesso', "Usuário criado com sucesso!");
    			}
    			catch (Exception $e) {
    				 
    			}
    		}
    		
    		return $this->redirect($this->generateUrl('contracultura_user_index'));
    	}
    }
    
    
    public function showProfileAction()
    {
    	return $this->render("PortalContraCulturaBundle:User:show.html.twig");    	
    }
    
    public function editProfileAction()
    {    
    	// Redirecionamento do botão "voltar" para o formulário de edição
    	$action = "profile";
    	
    	$form = $this->createForm(new UserType(), $this->getUser());
    	return $this->render('PortalContraCulturaBundle:User:user.html.twig', array (
    			'form' => $form->createView(),
    			'back_action' => $action,
				'user' => $this->getUser(),
    	));
    }
}
